from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from Store.models import *

import hashlib
def setpassword(password):
    md5 = hashlib.md5()
    md5.update(password.encode())
    result = md5.hexdigest()
    return result

def LoginValid(func):
    def inner(request,*args,**kwargs):
        cookie_userid = request.COOKIES.get("userid")
        session_userid = request.session.get("userid")
        cookieusername = request.COOKIES.get("username")
        if cookie_userid and session_userid:
            flag = QUser.objects.filter(
                id = session_userid,
                username = cookieusername
            ).exists()
            if flag:
                return func(request,*args,**kwargs)
        return HttpResponseRedirect("/login/")
    return inner

def reqtest(request):
    print(request.method)
    print(request.POST.get("username"))
    return render(request,"demo.html",locals())

from .forms import RegisterForm
def register(request):
    message = ""
    if request.method == "POST":
        # print(request.POST)
        registerform = RegisterForm(request.POST)
        if registerform.is_valid():
            data = registerform.cleaned_data
            username = data.get("username")
            email = request.POST.get("email")
            password = request.POST.get("password")
            repassword = request.POST.get("repassword")
            if password and password==repassword:
                flag = QUser.objects.filter(username=username).exists()
                if not flag:
                    QUser.objects.create(
                        username=username,
                        email=email,
                        password=setpassword(password),
                    )
                    # 重定向
                    return HttpResponseRedirect("/login/")
                else:
                    message = "账号已存在"
            else:
                message = "密码不符合"
        else:
            errors = registerform.errors

    return render(request,"register.html",locals())

def login(request):
    message = ""
    if request.method == "POST":
        # print(request.POST)
        username = request.POST.get("username")
        password = request.POST.get("password")
        if username and password:
            flag = QUser.objects.filter(
                username=username,
                password=setpassword(password)
            ).first()
            if flag:
                resp = HttpResponseRedirect("/index/")
                resp.set_cookie("username",flag.username)
                resp.set_cookie("userpicture",flag.picture)
                resp.set_cookie("userid",flag.id)
                request.session["userid"] = flag.id
                return resp
            else:
                message = "账号不存在，请先注册"
    return render(request,"login.html",locals())

from .forms import UserInfoForm
def userinfo(request,id):
    q_user = QUser.objects.filter(id=id).first()
    if request.method == "POST":
        # print(request.POST)
        userinfoform = UserInfoForm(request.POST)  # 实例化forms类，并传递获取的数据
        if userinfoform.is_valid():
            data = userinfoform.cleaned_data
            # 处理 保存数据
            q_user.nickname = data.get("nick_name")
            gender = request.POST.get("gender")
            if gender == "":
                gender = q_user.gender
            q_user.gender = gender
            q_user.phone = data.get("phone")
            q_user.email = data.get("email")
            q_user.address = data.get("address")
            if request.FILES.get("picture"):
                q_user.picture = request.FILES.get("picture")
            q_user.save()
            return HttpResponseRedirect("/index/")
        else:
            errors = UserInfoForm.errors
            print(errors)
        # 处理校验结果
    return render(request,"userinfo.html",locals())

def logout(request):
    resp = HttpResponseRedirect("/login/")
    resp.delete_cookie("userid")
    resp.delete_cookie("username")
    del request.session["userid"]
    return resp

@LoginValid
def index(request):
    return render(request,"index.html",locals())

def goods(request):
    return render(request,"goods.html",locals())

def statistics_goods(request):
    return render(request,"statistics_goods.html",locals())

def statistics_orders(request):
    return render(request,"statistics_orders.html",locals())

def store(request):
    return render(request,"store.html",locals())

def orders(request):
    return render(request,"orders.html",locals())

def set_cookie(request):
    resp = HttpResponse("设置cookie")
    resp.set_cookie("name","zs")
    return resp

def get_cookie(request):
    data = request.COOKIES
    print(data.get("name"))
    return HttpResponse("获取cookie")

def delete_cookie(request):
    resp = HttpResponse("删除cookie")
    resp.delete_cookie("name")
    return resp

def set_session(request):
    request.session["age"] = 12
    request.session.set_expiry(120) # 有效期
    return HttpResponse("设置session")

def get_session(request):
    data = request.session.get("name")
    print(data)
    return HttpResponse("获取session")

def delete_session(request):
    del request.session["name"]
    return HttpResponse("删除session")

from .forms import PersonForm
def test_form(request):
    # personform = PersonForm()
    if request.method == "POST":
        print(request.POST)
        # 获取数据
        # 后端校验
        personform = PersonForm(request.POST)    #实例化forms类，并传递获取的数据
        if personform.is_valid():
            # True代表校验通过
            print("success")
            # 处理数据 获取通过校验之后的数据
            data = personform.cleaned_data
            print(data)
            # 处理 保存数据
        else:
            # False 代表校验失败
            print("error")
            errors = personform.errors
            print(errors)
        # 处理校验结果
    return render(request,"forms.html",locals())

from django.http import JsonResponse
def jsontest(request):
    res = {"code":1000,"name":"zs"}
    for key,value in res.items():
        print(key,value)
    # res = ["code",1000]
    return JsonResponse(res)

def ajaxtest(request):
    result = {
        "code":"10000",
        "msg":"请求成功",
        "data":{}
    }
    userid = request.GET.get("id")
    person = QUser.objects.filter(id=userid).first()
    result["data"] = {
        "username":person.username,
        "password":person.password,
        "nickname":person.nickname,
        "picture":str(person.picture),
    }
    resp = JsonResponse(result)
    resp["Access-Control-Allow-Origin"] = "*"
    return resp

def vuedemo(request):
    return render(request,"vuedemo.html")

def list(request):
    return render(request,"list.html")

def list_login(request):
    result = {
        "data":[
        ]
    }
    goods_list = Goods.objects.filter()[0:8]
    print(goods_list)

    for one in goods_list:
        # print(one)
        data = {"g_name":one.g_name,"g_price":one.g_price,"g_picutre":str(one.g_picutre)}
        result["data"].append(data)
    print(result)
    return JsonResponse(result)


def list_login1(request):
    result = {
        "data":[]
    }
    goods_list = Goods.objects.filter()[0:8]
    print(goods_list)
    for one in goods_list:
        result["data"].append({
            "g_name":one.g_name,
            "g_price":one.g_price,
            "g_picutre":str(one.g_picutre)
        })
        print()
    return JsonResponse(result)

from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def fundemo(request):
    if request.method == "GET":
        return JsonResponse({"methods":"get"})

    if request.method == "POST":
        return JsonResponse({"methods":"post"})

    if request.method == "PUT":
        return JsonResponse({"methods":"puT"})

    import json
    if request.method == "DELETE":
        return JsonResponse({"methods":"delete"})

from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.views import View
@method_decorator(csrf_exempt,'dispatch')
class GoodsView(View):
    #封装init方法
    def __init__(self):
        self.result = {
            "code":"200",
            "msg":"success",
            "data":[],
            "methods":""
        }
    # 处理get请求
    def get(self,request):
        # 获取数据
        # 有参数
        self.result["methods"] = "get"
        id = request.GET.get('id')
        if id:
            # 处理id
            goods_obj = Goods.objects.filter(id=id).first()
            self.result["data"] = {
                "g_name":goods_obj.g_name,
                "g_number":goods_obj.g_number,
                "g_price":goods_obj.g_price,
                "g_description":goods_obj.g_description
            }
        else:

            # 没有参数
            goods_list = Goods.objects.all()[:12]
            for one in goods_list:
                goods_obj = {
                    "g_name":one.g_name,
                    "g_number":one.g_number,
                    "g_price":one.g_price,
                    "g_description":one.g_description,
                }
                self.result["data"].append(goods_obj)
        return JsonResponse(self.result)

    # 处理post请求
    def post(self,request):
        # 创建数据
        # 获取数据
        data = request.POST
        # 添加数据
        goods_obj = Goods()
        goods_obj.g_name = data.get("g_name")
        goods_obj.g_number = data.get("g_number")
        goods_obj.g_price = data.get("g_price")
        goods_obj.g_description = data.get("g_description")
        goods_obj.g_safe_date = data.get("g_safe_date")
        goods_obj.g_picutre = data.get("g_picutre")
        goods_obj.g_num = data.get("g_num")
        goods_obj.save()
        self.result["methods"] = "post"
        return JsonResponse(self.result)

    # 处理put请求
    def put(self,request):
        # 更新数据
        data = request.body   #bytes类型
        data = request.body.decode()   # 字符串类型json
        import json
        # # 第一种
        # data = json.loads(request.body.decode())
        # id = data.get("id")
        # goods = Goods.objects.filter(id = id).first()
        # data.pop("id")
        # for key,value in data.items():
        #     # 设置属性 为对象重新赋值 修改
        #     # 判断 获取到的key 是否为对象的属性
        #     if hasattr(goods,key):
        #         setattr(goods,key,value)
        # goods.save()

        # 第二种
        data = json.loads(request.body.decode())
        id = data.get("id")
        data.pop("id")
        # 修改数据
        Goods.objects.filter(id = id).update(**data)
        return JsonResponse(self.result)

    # 处理delete请求

    def delete(self,request):
        # 删除数据
        import json
        id = json.loads(request.body.decode()).get("id")
        Goods.objects.filter(id=id).delete()
        return JsonResponse({"methods":"delete"})



# # DRF
# # 1、APIView
from rest_framework.views import APIView,Response
from .serializer import MoreListSerializer
# # class MorelistView(APIView):
#     # 处理get请求
#     def get(self,request):
#         # 返回10条数据
#         goods_list = Goods.objects.all()[:10]
#         serializer = MoreListSerializer(goods_list,many=True)   #many=True结果中使用列表得形式
#         result = serializer.data  # 要返回的数据
#         return Response(result)
#
from rest_framework.views import APIView,Response
from .serializer import QuserListSerializer
class QuserlistView(APIView):
    # 处理get请求
    def get(self,request):
        # 返回10条数据
        user_list = QUser.objects.all()[:10]
        serializer = QuserListSerializer(user_list,many=True)   #many=True结果中使用列表得形式
        result = serializer.data  # 要返回的数据
        return Response(result)



# 2、mixins类
# from rest_framework import mixins,generics
# class MorelistView(mixins.ListModelMixin,generics.GenericAPIView):
#     def get_queryset(self):
#         # # 获取到一个queryset结果
#         # goods_list = Goods.objects.all()[:10]
#         # 返回某个商品的10条数据
#         type_id = self.request.GET.get("type_id")
#         goods_list = GoodsType.objects.filter(id = type_id).first().goods_set.all()
#         return goods_list
#     # 序列化器
#     serializer_class = MoreListSerializer
#
#     def get(self,request, *args, **kwargs):
#         # 处理get请求
#         return self.list(request, *args, **kwargs)
#
#     # 返回数据 让结果保持原有的样子
#     def get_serializer_context(self):
#         return {
#             "view":self
#         }




# # 3、通用视图类
# from rest_framework import generics
# class MorelistView(generics.ListAPIView):
#     def get_queryset(self):
#         # 获取到一个queryset结果
#         # goods_list = Goods.objects.all()[:10]
#         # 返回某个商品的10条数据
#         type_id = self.request.GET.get("type_id")
#         goods_list = GoodsType.objects.filter(id = type_id).first().goods_set.all()
#         return goods_list
#     # 序列化器
#     serializer_class = MoreListSerializer
#
#     # 返回数据 让结果保持原有的样子
#     def get_serializer_context(self):
#         return {
#             "view":self
#         }



# 4、ViewSet类和路由器
from rest_framework import viewsets
class MorelistView(viewsets.ReadOnlyModelViewSet):
    def get_queryset(self):
        # 获取到一个queryset结果
        # goods_list = Goods.objects.all()[:10]
        # 返回某个商品的10条数据
        type_id = self.request.GET.get("type_id")
        goods_list = GoodsType.objects.filter(id = type_id).first().goods_set.all()
        return goods_list
    # 序列化器
    serializer_class = MoreListSerializer

    # 返回数据 让结果保持原有的样子
    def get_serializer_context(self):
        return {
            "view":self
        }











# import random
# from django.http import HttpResponse
# def add_goods(request):
#     ## 添加店铺
#     store = Store.objects.create(s_name="生鲜店", s_logo="1.jpg", s_address="北京", s_description="北京生鲜店",
#                                  s_user=QUser.objects.get(id=1))
#     ## 添加类型
#     goodstype = GoodsType.objects.create(t_name="生鲜", t_description="生鲜店",t_img="1.jpg")
#     ## 增加100 条  
#     goods_name = "芹菜、西芹、菠菜、香菜、茼蒿、茴香、生菜、苋菜、莴苣、葱、香葱、分葱、胡葱、楼子葱、蒜头、洋葱头、韭菜、韭葱、黄瓜、丝瓜、冬瓜、菜瓜、苦瓜、南瓜、栉瓜、西葫芦、葫芦、瓠瓜、节瓜、越瓜、笋瓜、佛手瓜"
#     goods_name = goods_name.split("、")
#     address = "北京市，天津市，上海市，重庆市，河北省，山西省，辽宁省，吉林省，黑龙江省，江苏省，浙江省，安徽省，福建省，江西省，山东省，河南省，湖北省，湖南省，广东省，海南省，四川省，贵州省，云南省，陕西省，甘肃省，青海省，台湾省"
#     address = address.split("，")
#     for n in range(10):
#         for i, j in enumerate(range(10), 1):  ## i 是索引 代表下标从1开始
#             goods = Goods()
#             goods.g_number = str(i).zfill(5)  ## 返回指定长度的字符串   长度是5 
#             goods.g_name = random.choice(address) + random.choice(goods_name)  ###从列表中随机取一个值  
#             goods.g_price = round(random.random() * 100, 2)  ## 0到1 的小数  
#             goods.g_num = random.randint(1, 100)
#             goods.g_safe_date = random.randint(1, 12)
#             goods.g_desription = "很好"
#             goods.g_picutre = "images/goods.jpg"
#             goods.g_type = goodstype
#             goods.g_store = store
#             goods.save()
#     return HttpResponse("添加数据")










